﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Singer.Core;
using Singer.Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Singer.Framework.CoreFilters
{
    public class CoreApiExceptionFilter : IAsyncExceptionFilter
    {
        public Task OnExceptionAsync(ExceptionContext context)
        {
            if (context.ExceptionHandled == false)//异常没有被处理
            {
                IWebHostEnvironment env = context.HttpContext.RequestServices.GetRequiredService<IWebHostEnvironment>();
                string msg = context.Exception.Message;
                if (env.IsDevelopment())
                {
                    //如果不是手动抛出的业务异常。认为是系统未处理的异常，在开发环境显示详细堆栈信息，方便找问题。
                    if (context.Exception is not CoreException)
                        msg += "【异常堆栈】(仅开发环境可见)：" + context.Exception.StackTrace;
                }
                CoreApiResult result = CoreApiResult.Error(msg);
                if (context.Exception is CoreException exp)
                    result.SetErrorCode(exp.Code);
                context.Result = new ContentResult
                {
                    StatusCode = StatusCodes.Status200OK,//http状态码设置为200，表示成功
                    ContentType = "application/json;charset=utf-8",//设置数据格式
                    Content = JsonUtils.ToJson(result)
                };
            }
            context.ExceptionHandled = true;//设置为true，表示异常已经被处理了
            return Task.CompletedTask;
        }
    }
}
